﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace QCYHApp
{
    class AppUitls
    {
        InitFile init = new InitFile();
        MsSqlHelper mssql = new MsSqlHelper();

       private static string apiKey = InitFile.apiKey;
       private static string apiSecret = InitFile.apiSecret;
       private static string timeStamp = InitFile.GetTimeStamp();
       private string sign = InitFile.md5(apiKey + apiSecret + timeStamp);

        public DataTable dataTable;
        public string result = "";
        public int number = 0;
        public string title = "";

        public void SyncStr(string SendPostName, string BatchNo = "", string StartDate = "", string EndDate = "")
        {
            string sql = "";
            try
            {
                if (SendPostName == "SendPostDrug")
                {
                    sql = "select rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,"
                        + " rtrim(a.imageid) as imageid,rtrim(a.detailid) as detailid,'http://khoa.scjrm.com:86/'+a.url as url,"
                        + " 23 as qualification_type_id "
                        + " from imagedoc a(nolock) "
                        + " left join spkfk b(nolock) on a.detailid=b.spid "
                        + " where a.leibie='注册批件' and isnull(a.folderpath,'')<>'√' and a.lastmodifytime>='2021-01-01'";
                    if (!string.IsNullOrEmpty(StartDate))
                    {
                        sql += " and a.lastmodifytime>'" + StartDate + "' ";
                    }
                    if (!string.IsNullOrEmpty(EndDate))
                    {
                        sql += " and a.lastmodifytime<='" + EndDate + "' ";
                    }
                    if (!string.IsNullOrEmpty(BatchNo))
                    {
                        sql += " and right(rtrim(a.imageid),1)='" + BatchNo + "'";
                    }
                    sql += " order by a.imageid desc";
                }
                if (SendPostName == "SendPostBatch")
                {
                    sql = "select top 5000 rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,"
                        + " rtrim(a.imageid) as imageid,rtrim(a.detailid) as detailid,a.fzxx1 as batchid,'http://khoa.scjrm.com:86/'+a.url as url,"
                        + " rtrim(a.detailid)+rtrim(a.fzxx1) as drugBatchId "
                        + " from imagedoc a(nolock) "
                        + " left join spkfk b(nolock) on a.detailid=b.spid "
                        + " where a.leibie='检验报告' and isnull(a.folderpath,'')<>'√' and a.lastmodifytime>='2021-01-01'";
                    if (!string.IsNullOrEmpty(StartDate))
                    {
                        sql += " and a.lastmodifytime>'" + StartDate + "' ";
                    }
                    if (!string.IsNullOrEmpty(EndDate))
                    {
                        sql += " and a.lastmodifytime<='" + EndDate + "' ";
                    }
                    if (!string.IsNullOrEmpty(BatchNo))
                    {
                        sql += " and right(rtrim(a.imageid),1)='" + BatchNo + "'";
                    }
                    sql += " order by a.imageid desc";
                }
                dataTable = mssql.ExecuteDt(sql);
                title = "_"+SendPostName + "_" + BatchNo + "_" + StartDate + "_" + EndDate;
                number = dataTable.Rows.Count;
            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(),true);
            }
        }

        public void SyncStr(DataTable dt)
        {
            dataTable = dt;
            title = "选中数据上传";
            number = dataTable.Rows.Count;
        }
        

        public void HotSync(BackgroundWorker bw, DoWorkEventArgs e)
        {
            string sql = "";
            string ret = "";

            for (int i = 0; i < number; i++)
            {
                if (bw.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                string drugId = dataTable.Rows[i]["detailid"].ToString().Trim();
                string file = dataTable.Rows[i]["url"].ToString().Trim();
                string imageid = dataTable.Rows[i]["imageid"].ToString().Trim();
                bool istrue = mssql.GetBool("select top 1 1 from imagedoc(nolock) where isnull(folderpath,'')<>'√' and imageid='" + imageid + "'");
                if (istrue)
                {
                    if (e.Argument.ToString() == "SendPostDrug")
                    {
                        try
                        {
                            string qualification_type_id = dataTable.Rows[i]["qualification_type_id"].ToString().Trim();
                            ret = uploaderDurg(drugId, qualification_type_id, file);
                        }
                        catch (Exception ex)
                        {
                            init.WriteLog(ex.ToString(), true, title);
                            result = "[Error]:【" + i + "】" + ex.Message + "\r\n";
                        }
                    }
                    if (e.Argument.ToString() == "SendPostBatch")
                    {
                        try
                        {
                            string batchid = dataTable.Rows[i]["batchid"].ToString().Trim();
                            string drugBatchId = dataTable.Rows[i]["drugBatchId"].ToString().Trim();
                            ret = uploaderBatch(drugBatchId, file);
                        }
                        catch (Exception ex)
                        {
                            init.WriteLog(ex.ToString(), true, title);
                            result = "[Error]:【" + i + "】" + ex.Message + "\r\n";
                        }
                    }
                    //init.WriteLog(ret.ToString(), false, title);
                    try
                    {
                        sql = "update imagedoc set folderpath='√',fzxx2=rtrim('" + ret + "') where isnull(folderpath,'')<>'√' and imageid='" + imageid + "'";
                        if (mssql.ExecuteSql(sql) > 0)
                        {
                            result = "【" + drugId + "】" + imageid + "[" + ret + "]\r\n";
                        }
                    }
                    catch (Exception ex)
                    {
                        init.WriteLog(ex.ToString(), true,title);
                        result = "[Error]:【" + drugId + "】" + imageid + "[" + ret + "]\r\n";
                        continue;
                    }
                }                
                bw.ReportProgress(i + 1, String.Format("{0}%", i + 1));
                Thread.Sleep(100);
            }
            init.WriteLog("更新" + title + "数据" + number + "条", false, title);
        } 
        

        #region 批件资料上传
        /// <summary>
        /// 批件资料上传
        /// </summary>
        /// <param name="drugId">商品内置id</param>
        /// <param name="qualification_type_id"></param>
        /// <param name="file">多个图片路径用逗号,区分开</param>
        /// 23	药品注册批件
        /// 24	药品再注册批件
        /// 25	药品补充批件
        /// 26	药品质量执行标准
        /// 27	新药证书
        /// 28	物件批件
        /// 29	使用说明书
        /// 30	包装样式
        /// 31	标签
        /// 32	药品容器材质说明
        /// 33	药品检验报告
        /// 34	商标注册证
        /// 35	核准续展证明
        /// 36	商标使用许可证
        /// 37	专利证书
        /// 38	进口药品注册证/医药产品注册证
        /// 39	进出口通关单
        /// 40	进口药品检验报告
        /// 41	进口药材批件
        /// 42	包装书/说明书/注射液标签等在药监局盖章的备案
        /// 43	其它
        /// 50	厂家批件变更
        /// 59	医疗器械注册证
        /// 60	商品档案
        /// 69	消毒产品卫生安全评价报告
        /// 251	厂家资料
        /// <returns>返回上传状态</returns>

        public string uploaderDurg(string drugId, string qualification_type_id, string file)
        {
            string url = InitFile.url + "Uploader/uploaderDurg";
            /* 
            string apiKey = InitFile.apiKey;
            string apiSecret = InitFile.apiSecret;
            string timeStamp = InitFile.GetTimeStamp();
            string sign = InitFile.md5(apiKey + apiSecret + timeStamp);
             */

            List<HttpUitls.FormItemModel> formItems = new List<HttpUitls.FormItemModel>();
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiKey", Value = apiKey });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiSecret", Value = apiSecret });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "sign", Value = sign });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "timeStamp", Value = timeStamp });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "drugId", Value = drugId });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "qualification_type_id", Value = qualification_type_id });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "file", Value = file });
            string result = init.FromUnicodeString(HttpUitls.PostForm(url, formItems));
            return result;
        }
        #endregion

        #region 检验报告资料上传
        /// <summary>
        /// 检验报告资料上传
        /// </summary>
        /// <param name="drugBatchId">商品内置id+批号（无缝拼接）</param>
        /// <param name="file">多个图片路径用逗号,区分开</param>
        /// <returns>返回上传状态</returns>
        public string uploaderBatch(string drugBatchId, string file)
        {
            string url = InitFile.url + "Uploader/uploaderBatch";
            /*
            string apiKey = InitFile.apiKey;
            string apiSecret = InitFile.apiSecret;
            string timeStamp = InitFile.GetTimeStamp();
            string sign = InitFile.md5(apiKey + apiSecret + timeStamp);
             */

            List<HttpUitls.FormItemModel> formItems = new List<HttpUitls.FormItemModel>();
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiKey", Value = apiKey });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiSecret", Value = apiSecret });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "sign", Value = sign });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "timeStamp", Value = timeStamp });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "drugBatchId", Value = drugBatchId });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "file", Value = file });
            string result = init.FromUnicodeString(HttpUitls.PostForm(url, formItems));
            return result;
        }
        #endregion

        #region 通过接口获取首营企业资料
        public string getdowntranslate()
        {
            string url = InitFile.url + "/Business/translate";
            string start = "";
            string end = "";

            List<HttpUitls.FormItemModel> formItems = new List<HttpUitls.FormItemModel>();
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiKey", Value = apiKey });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "apiSecret", Value = apiSecret });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "sign", Value = sign });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "timeStamp", Value = timeStamp });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "start", Value = start });
            formItems.Add(new HttpUitls.FormItemModel() { Key = "end", Value = end });
            string result = init.FromUnicodeString(HttpUitls.PostForm(url, formItems));
            return result;
        }
        #endregion
    }
}
